package com.hht.baselibs.layoutManager

import android.os.Build
import android.util.DisplayMetrics
import android.view.View
import androidx.annotation.RequiresApi
import androidx.recyclerview.widget.LinearSmoothScroller
import androidx.recyclerview.widget.RecyclerView
import com.hht.baselibs.layoutManager.RecycleViewLayoutManager
import com.hht.baselibs.layoutManager.RecycleViewPagerConfig


/**
 * Author:chen'hu
 * Time:2023/8/10 14:21
 * Description:用于处理平滑滚动
 */
class RecycleViewSmoothScroller(var recyclerView: RecyclerView) :
    LinearSmoothScroller(recyclerView.context) {

    override fun onTargetFound(targetView: View, state: RecyclerView.State, action: Action) {
        val manager = recyclerView.layoutManager ?: return
        if (manager is RecycleViewLayoutManager) {
            val layoutManager: RecycleViewLayoutManager = manager
            val pos = recyclerView.getChildAdapterPosition(targetView)
            val snapDistances: IntArray = layoutManager.getSnapOffset(pos)!!
            val dx = snapDistances[0]
            val dy = snapDistances[1]
//            "dx = $dx  dy = $dy".showLog(2)
            val time = calculateTimeForScrolling(Math.max(Math.abs(dx), Math.abs(dy)))
            if (time > 0) {
                action.update(dx, dy, time, mDecelerateInterpolator)
            }
        }
    }


    @RequiresApi(Build.VERSION_CODES.DONUT)
    override fun calculateSpeedPerPixel(displayMetrics: DisplayMetrics): Float {
        return RecycleViewPagerConfig.getMillisecondsPreInch() / displayMetrics.densityDpi
    }
}